<template>
  <div>
    <div class="tools-div">
      <el-button type="success" size="small" @click="dialogVisible = true">
        添 加
      </el-button>
    </div>

    <el-table :data="list" style="width: 100%">
      <el-table-column prop="specName" label="规格名称" />
      <el-table-column label="规格值" #default="scope" width="400">
        <div
          v-for="(item1, index1) in scope.row.specValue"
          :key="index1"
          style="padding: 5px; margin: 0;width: 100%;"
        >
          {{ item1.key }}：
          <span
            v-for="(item2, index2) in item1.valueList"
            :key="index2"
            class="div-atrr"
          >
            {{ item2 }}
          </span>
        </div>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" align="center" width="200" #default="scope">
        <el-button
          type="primary"
          size="small"
          @click="handleShowEditDialog(scope.row)"
        >
          修改
        </el-button>
        <el-button type="danger" size="small" @click="handleDel(scope.row)">
          删除
        </el-button>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[1, 2, 3, 4, 5]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="initData"
      @current-change="initData"
    />

    <!-- 新增更新规格参数的对话框 -->
    <div>
      <el-dialog v-model="dialogVisible" title="添加或修改" width="40%">
        <el-form label-width="120px">
          <el-form-item label="规格名称">
            <el-input v-model="productSpec.specName" />
          </el-form-item>
          <el-form-item>
            <el-button
              size="default"
              type="success"
              @click="productSpec.specValue.push({})"
            >
              添加新规格
            </el-button>
          </el-form-item>
          <el-form-item
            label=""
            v-for="(item, index) in productSpec.specValue"
            :key="index"
          >
            <el-row>
              <el-col :span="10">
                <el-input
                  v-model="item.key"
                  placeholder="规格"
                  style="width: 90%;"
                />
              </el-col>
              <el-col :span="10">
                <el-input
                  v-model="item.valueList"
                  placeholder="规格值(如:白色,红色)"
                  style="width: 90%;"
                />
              </el-col>
              <el-col :span="4">
                <el-button
                  size="default"
                  type="danger"
                  @click="productSpec.specValue.splice(index, 1)"
                >
                  删除
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item align="right">
            <el-button type="primary" @click="handleSaveOrUpdate">
              提交
            </el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  GetAllSpecs,
  GetSpecsById,
  DeleteSpecsById,
  UpdateSpecs,
  GetSpecs,
  SaveSpecs,
} from '@/api/productSpec'
//4、更新
//回显要更新的数据弹出对话框
const handleShowEditDialog = row => {
  productSpec.value = JSON.parse(JSON.stringify(row))
  dialogVisible.value = true
}
//提交更新请求
const handleUpdate = async () => {
  if (productSpec.value.specValue) {
    productSpec.value.specValue.forEach(specValue => {
      //判断 如果specValue.valueList的类型是字符串，调用split否则不调用
      if (typeof specValue.valueList === 'string') {
        specValue.valueList = specValue.valueList.split(',')
      }
    })
  }
  productSpec.value.specValue = JSON.stringify(productSpec.value.specValue)
  await UpdateSpecs(productSpec.value)
  ElMessage.success('更新成功')
  initData()
  dialogVisible.value = false
}
//3、新增
const dialogVisible = ref(false)
const productSpec = ref({
  specValue: [],
})
const handleSave = async () => {
  //productSpec = {"specValue":[{"key":"轴体类型","valueList":"红,黑,茶"},{"key":"接口类型","valueList":"无线,有线"}],"specName":"键盘"}
  //1、先将productSpec的每一个specValue的 valueList收集的字符串转为 json数组
  console.log(productSpec.value)
  if (productSpec.value.specValue) {
    productSpec.value.specValue.forEach(specValue => {
      specValue.valueList = specValue.valueList.split(',')
    })
  }
  console.log(productSpec.value)
  //2、再将productSpec的specValue转为json字符串
  productSpec.value.specValue = JSON.stringify(productSpec.value.specValue)
  console.log(productSpec.value)
  await SaveSpecs(productSpec.value)
  ElMessage.success('新增成功')
  initData()
  dialogVisible.value = false
}
const handleSaveOrUpdate = () => {
  if (productSpec.value.id) {
    handleUpdate()
  } else {
    handleSave()
  }
}
//2、删除
const handleDel = async row => {
  await DeleteSpecsById(row.id)
  ElMessage.success('删除成功')
  initData()
}
//1、初始化页面数据
const pageNum = ref(1)
const pageSize = ref(3)
const total = ref(0)
const list = ref([])
const initData = async () => {
  const { data } = await GetSpecs(pageNum.value, pageSize.value)
  list.value = data.list
  //查询到的规格参数值  属性值 后端返回的是json字符串，遍历时遍历的是字符
  //需要将后端返回的json数组字符串 转为json数组 上面遍历才可以正常展示
  list.value.forEach(spec => {
    //spec: spec包含 specName 和specValue
    spec.specValue = JSON.parse(spec.specValue)
  })
  total.value = data.total
}
onMounted(() => {
  initData()
})
</script>

<style scoped>
.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.div-atrr {
  padding: 5px 10px;
  margin: 0 10px;
  background-color: powderblue;
  border-radius: 10px;
}
</style>
